﻿using HDM.NexusEngine.Core;
using HDM.NexusEngine.Input;
using Tao.OpenGl;
using Tao.Sdl;

namespace HDM.NexusEngine.EngineTest
{
    public class InputTestState : IGameObject
    {
        private readonly bool _useJoystick;
        private readonly XboxController _controller;

        public InputTestState()
        {
            Sdl.SDL_InitSubSystem(Sdl.SDL_INIT_JOYSTICK);
            if (Sdl.SDL_NumJoysticks() <= 0) return;

            // Start using the joystick code.
            _useJoystick = true;
            _controller = new XboxController(0);
        }

        public void Update(double elapsedTime)
        {
            if(_useJoystick == false) return;

            Sdl.SDL_JoystickUpdate();
            _controller.Update();
        }

        public void Render()
        {
            if (_useJoystick == false) return;

            Gl.glDisable(Gl.GL_TEXTURE_2D);
            Gl.glClearColor(1, 1, 1, 0);

            Gl.glClear(Gl.GL_COLOR_BUFFER_BIT);
            Gl.glPointSize(10.0f);
            Gl.glBegin(Gl.GL_POINTS);
            {
                Gl.glColor3f(1, 0, 0);
                Gl.glVertex2f(_controller.LeftControlStick.X*300, _controller.LeftControlStick.Y*-300);
                Gl.glColor3f(0, 1, 0);
                Gl.glVertex2f(_controller.RightControlStick.X*300, _controller.RightControlStick.Y*-300);

                Gl.glColor3f(0.5f, 0, 0);
                Gl.glVertex2f(-50, _controller.LefTrigger.Value*300);
                Gl.glColor3f(0, 0.5f, 0);
                Gl.glVertex2f(50, _controller.RighTrigger.Value*300);

                DrawButtonPoint(_controller.ButtonA.Held, 300);
                DrawButtonPoint(_controller.ButtonB.Held, 280);
                DrawButtonPoint(_controller.ButtonX.Held, 260);
                DrawButtonPoint(_controller.ButtonY.Held, 240);
                DrawButtonPoint(_controller.ButtonLB.Held, 220);
                DrawButtonPoint(_controller.ButtonRB.Held, 200);
                DrawButtonPoint(_controller.ButtonBack.Held, 180);
                DrawButtonPoint(_controller.ButtonStart.Held, 160);
                DrawButtonPoint(_controller.ButtonL3.Held, 140);
                DrawButtonPoint(_controller.ButtonR3.Held, 120);

                DrawButtonPoint(_controller.Dpad.UpHeld, 80);
                DrawButtonPoint(_controller.Dpad.DownHeld, 60);
                DrawButtonPoint(_controller.Dpad.LeftHeld, 40);
                DrawButtonPoint(_controller.Dpad.RightHeld, 20);
            }
            Gl.glEnd();
        }

        private void DrawButtonPoint(bool held, int yPos)
        {
            Gl.glColor3f(0, held ? 1 : 0, 0);
            Gl.glVertex2f(-400, yPos);
        }
    }
}